package com.baizhi.cmfz.realm;

import com.baizhi.cmfz.entity.Admin;
import com.baizhi.cmfz.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * 授权领域，授权需要认证，所以继承了授权领域也就实现了认证领域的方法
 */
public class AuthorRealm extends AuthorizingRealm {
    @Autowired
    private AdminService adminService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1 获取身份信息 参数中给的是个集合，因为用户可能有几个账号获取主账号
        String username = (String) principalCollection.getPrimaryPrincipal();
        //2 查数据库，获取到角色和权限
        Set<String> roles = adminService.selectAdminRole(username);
        Set<String> permisions = adminService.selectAdminPermision(username);
        //3 封装info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permisions);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1 获取到封装到token中的username
        /*UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();*/
        String username = (String) authenticationToken.getPrincipal();
        //2 查询数据库
        Admin admin = adminService.selectOneAdmin(username);
        //3 封装info
        if (admin != null) {
            return new SimpleAuthenticationInfo(admin.getUsername(),admin.getPassword(),this.getName());
        }
        return null;
    }
}
